#ifndef FILESOCKET_H
#define FILESOCKET_H

#include <QObject>
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QByteArray>
#include <QFile>
#include "widget.h"

//文件上传下载的字段定义
#define FILE_UPLOAD_HEADER             100
#define FILE_UPLOAD_POS                101
#define FILE_UPLOAD_TAIL               103
#define FILE_DOWNLOAD_HEADER           200
#define FILE_DOWNLOAD_CONTENT          202
#define FILE_DOWNLOAD_TAIL             203

//错误码定义
#define OK                             0
#define FILE_WRITE_ERROR               -1
#define FILE_OPEN_ERROR                -2
#define FILE_SEEK_ERROR                -3
#define FILE_ALREADY_EXISTS_ERROR      -4
#define RECV_DATA_TIMEOUT_ERROR        -5
#define RECV_UNKNOW_DATA_ERROR         -6
#define CONNECT_SERVER_ERROR           -7
#define UPLOAD_FILE_ERROR              -8
#define DOWNLOAD_FILE_ERROR            -10


class FileSocket : public QObject
{
    Q_OBJECT
public:
    explicit FileSocket(QObject *parent = 0);
    explicit FileSocket(qint32 param_id,qintptr param_socketDescriptor,QObject *parent = nullptr);
    ~FileSocket();

    QString g_root_dir;     //默认存储路径

signals:
    void socketClose(qint32); //当socket关闭的时候，向FileServer发送关闭信号

public slots:
    void socketError(QAbstractSocket::SocketError param_error);
    void socketDisconnect();

    //绑定readyRead信号，进行数据读取
    void fileRead();

    //文件数据处理
    void fileHandle(qint64 param_request_id,QMap<QString,QVariant>& param_qst_file,QMap<QString,QVariant>& param_rst_file,bool& reply);

protected:
    void paramInit();
    qint64 fileUploadHeader(QString filename,qint64& pos,QString& md5_value);
    qint64 fileUploadPos(qint64 file_pos);

    qint64 fileDownloadHeader(QString filename,qint64& pos,QString& md5_value,qint64& file_size);
    qint64 fileDownloadContent();



private:
    qint32 m_id;
    QTcpSocket m_socket;

    qint64 m_fileupload_state;      //文件上传中间状态标志，分为头尾处理状态和文件数据传输状态。
    qint64 m_file_totalBytes;
    qint64 m_file_pos;
    qint64 m_req_id;

    QByteArray m_msgBytes;
    QFile m_local_file;
    qint64 m_status;

};

#endif // FILESOCKET_H
